<script setup lang="tsx">
import { reactive, watch } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { usePagination } from '@sa/alova/client';
import { deletePermission, paginatePermission } from '@/service/api/manage';
import { $t } from '@/locales';
import useTableOperate from '@/hooks/common/table/table-operate';
import useCheckedColumns from '@/hooks/common/table/table-columns';
import { useAppStore } from '@/store/modules/app';
import PorDictTag from '@/components/_builtin/por-dict-tag/index.vue';
import ButtonOperateDrawer from './button-operate-drawer.vue';

defineOptions({
  name: 'ButtonListTable'
});

interface Props {
  /** select data */
  showData: Api.Manage.Menu;
}

const parentId = defineModel<number>('parentId', {
  default: 0
});

defineProps<Props>();

const appStore = useAppStore();

const searchParams = reactive({
  status: null,
  parentId: parentId.value
});

const { loading, data, refresh, page, pageSize, pageCount, send, remove } = usePagination(
  (pageNum, size) =>
    paginatePermission({
      ...searchParams,
      pageNumber: pageNum,
      pageSize: size
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,

    // trigger reload when states in `searchParams` changed
    watchingStates: [searchParams],

    // debounce of `searchParams`
    debounce: [100]
  }
);

const getDataByPage = (newPage = 1) => {
  page.value = newPage;
  send(page.value, pageSize.value);
};

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, handleDelete, checkedRowKeys } =
  useTableOperate(data, {
    async delete(row) {
      await deletePermission({ id: row.id });

      remove(row);
    }
  });

const { columns } = useCheckedColumns<typeof paginatePermission>(() => [
  {
    key: 'name',
    title: '名称',
    align: 'center',
    width: 150
  },
  {
    key: 'permissionKey',
    title: '权限 Key',
    align: 'center',
    width: 200
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    width: 50,
    render: row => {
      if (row.status === null) {
        return null;
      }

      return <PorDictTag dict-code="common_status" value={row.status} value-to-number />;
    }
  },
  {
    key: 'sortRank',
    title: '排序',
    align: 'center',
    width: 50
  },
  {
    key: 'remark',
    title: '备注',
    align: 'center',
    width: 120,
    ellipsis: {
      tooltip: true
    }
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 80,
    fixed: 'right',
    render: row => (
      <div class="flex-center gap-8px">
        {
          <NButton type="primary" ghost size="small" onClick={() => handleEditButton(row.id as number)}>
            {$t('common.edit')}
          </NButton>
        }
        {
          <NPopconfirm onPositiveClick={() => handleDelete(row.id as number)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        }
      </div>
    )
  }
]);

/** add permission button */
function handleAddButton() {
  handleAdd();
}

/** edit permission button */
function handleEditButton(id: number) {
  handleEdit(id);
}

// query permisson button data with menu id.
watch(parentId, () => {
  searchParams.parentId = parentId.value;
  getDataByPage();
});
</script>

<template>
  <div class="flex flex-grow">
    <NCard title="权限按钮" :bordered="false" size="small">
      <template #header-extra>
        <NButton type="primary" ghost size="small" @click="handleAddButton()">
          {{ $t('common.add') }}
        </NButton>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        remote
        striped
        size="small"
        class="sm:h-full"
        :data="data"
        :scroll-x="962"
        :columns="columns"
        :flex-height="!appStore.isMobile"
        :loading="loading"
        :single-line="false"
        :row-key="row => row.id"
        :pagination="{
          page,
          pageSize,
          showSizePicker: true,
          pageCount,
          pageSizes: [10, 15, 20, 25, 30],
          onUpdatePage(value) {
            page = value;
          },
          onUpdatePageSize(value) {
            pageSize = value;
          }
        }"
        min-height="200px"
      />
    </NCard>
    <ButtonOperateDrawer
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :menu-data="showData"
      :row-data="editingData"
      @submitted="refresh"
    />
  </div>
</template>
